import "./assets/main.css";
import { createApp } from "vue";
import { createPinia } from "pinia";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import App from "./App.vue";
import router from "./router";
import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";

// 判断是否运行在qiankun环境中
const isInQiankun = qiankunWindow.__POWERED_BY_QIANKUN__;

let app: any = null;

function render(props: any = {}) {
  const { container, routerBase } = props;
  console.log("Staff App render - container:", container);
  console.log("Staff App render - routerBase:", routerBase);
  console.log("Staff App render - window location:", window.location.href);

  // 如果是在主应用中被渲染，则挂载到主应用提供的容器中
  // 否则挂载到自身的#app节点上
  let renderContainer;
  
  if (container) {
    // 为子应用创建一个新的div作为挂载点
    // 清空容器内容
    container.innerHTML = '';
    const appDiv = document.createElement("div");
    appDiv.id = "staff-app-container";
    container.appendChild(appDiv);
    renderContainer = appDiv;
    console.log("Staff App - Using qiankun container");
  } else {
    renderContainer = document.getElementById("app");
    console.log("Staff App - Using local container #app");
  }

  if (!renderContainer) {
    console.error("Staff App - No container found!");
    return;
  }

  console.log("Staff App - Mounting to:", renderContainer);
  
  app = createApp(App);
  
  // 在路由就绪前先输出当前URL，方便调试
  console.log("Staff App - Current URL before router setup:", window.location.pathname);
  
  // 设置应用
  app.use(router).use(ElementPlus).use(createPinia());
  
  // 输出路由信息
  console.log("Staff App - Current routes:", router.getRoutes());
  console.log("Staff App - Current route:", router.currentRoute.value);
  
  // 设置全局属性 - 可从任何组件访问
  app.config.globalProperties.$isQiankun = isInQiankun;
  app.config.globalProperties.$mainProps = props;
  
  // 挂载应用
  app.mount(renderContainer);
  
  // 如果在qiankun中，尝试手动导航到首页确保内容显示
  if (isInQiankun) {
    // 使用setTimeout确保在挂载完成后执行
    setTimeout(() => {
      // 如果当前是根路径，尝试导航到home
      if (router.currentRoute.value.path === '/') {
        console.log("Staff App - Navigating to home route");
        router.push('/');
      }
    }, 100);
  }
}

// 判断是否为乾坤加载，如果不是直接渲染
if (!isInQiankun) {
  console.log("Staff App - 独立运行");
  render({});
} else {
  // 加载乾坤生命周期
  console.log("Staff App - qiankun 环境中运行");
  renderWithQiankun({
    mount(props) {
      console.log("Staff App - mount with props:", props);
      render(props);
    },
    bootstrap() {
      console.log("Staff App - bootstrap");
    },
    update(props) {
      console.log("Staff App - update:", props);
    },
    unmount(props) {
      console.log("Staff App - unmount:", props);
      app?.unmount();
    },
  });
}
